<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="filter-right">
        <el-button icon="el-icon-plus" type="primary" size="mini" @click="handleAdd">
          新增角色
        </el-button>
      </div>
    </div>
    <el-table
      v-loading="listLoading"
      :data="pageList"
      border
      fit
      stripe
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column type="index" label="序号" width="80" align="center" fixed/>
      <el-table-column
        prop="role_name"
        label="角色名称"
        align="left"
      >
      </el-table-column>
      <el-table-column
        prop="role_code"
        label="角色编码"
        align="center"
      >
      </el-table-column>
      <el-table-column label="创建时间" align="center" width="180">
        <template slot-scope="{ row }">
          <span>{{ row.created_at | formate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" width="180">
        <template slot-scope="{ row }">
          <span>{{ row.updated_at | formate }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center">
        <template slot-scope="scope">
          <el-button @click="handleModify(scope.row)" type="text" size="small"
            >修改</el-button
          >
          <el-button
            @click="handleDelete(scope.row)"
            type="text"
            size="small"
            v-if="checkPermission(['admin'])"
            style="color: red"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getPageList"
    />

    <!-- 新增角色 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" width="550px">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="角色名称" label-width="100px" prop="roleName">
          <el-input
            v-model="form.roleName"
            autocomplete="off"
            maxlength="20"
            @input="changeValue('roleName', '20')"
            placeholder="请输入角色名称"
          ></el-input>
        </el-form-item>
       
        <el-form-item label="角色编码" label-width="100px" prop="roleCode">
          <el-input
            autocomplete="off"
            maxlength="20"
            @input="changeValue('roleCode', '20')"
            placeholder="请输入角色编码"
            v-model="form.roleCode"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('form')">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import {
  getUserRoleLists,
  createdUserRole,
  updateUserRole,
  delUserRole,
} from "@/api/user-role";
import { checkUserToken } from "@/api/user";
import { curentTime } from "@/filters/index";
import waves from "@/directive/waves";
import Pagination from "@/components/Pagination";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import checkPermission from "@/utils/permission"; // 权限判断函数
export default {
  name: "user-role",
  components: { Pagination, Treeselect },
  directives: { waves },
  filters: {
    formate(date) {
      return curentTime(date);
    },
  },
  data() {
    return {
      // 项目数据
      pageList: [],
      // 项目总数
      total: 0,
      // 加载
      listLoading: true,
      // 查询参数
      listQuery: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单控制
      dialogFormVisible: false,
      dialogCharge: false,
      // 表单标题
      title: "",
      // 表单参数
      form: {
        roleName: "",
        roleCode: "",
        id: null
      },
      orderIDs: "",
      // 表单检验
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        roleCode: [
          { required: true, message: "请选择角色编码", trigger: "blur" },
        ],
      },
    };
  },
  async created() {
    await this.getPageList();
  },
  methods: {
    checkPermission,
    // 查询项目数据
    async getPageList() {
      try {
        const res = await getUserRoleLists(this.listQuery);
        this.total = res.data.totalItems;
        this.pageList = res.data.items;
        this.listLoading = false;
      } catch (error) {
        console.log(error);
      }
    },

    // 提交表单信息
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.form.id) {
            updateUserRole(this.form).then((res) => {
              this.$message({
                message: "修改成功",
                type: "success",
              });
              this.getPageList();
              this.dialogFormVisible = false;
            });
          } else {
            createdUserRole(this.form).then((res) => {
              this.$message({
                message: "新增成功",
                type: "success",
              });
              this.getPageList();
              this.dialogFormVisible = false;
            });
          }
        } else {
          return false;
        }
      });
    },
    // 取消
    resetForm(formName) {
      this.dialogFormVisible = false;
    },

    // 新增角色
    handleAdd() {
      checkUserToken().then((res) => {
        if(res.data) {
          this.title = "新增角色";
          this.$delete(this.form, "id");
          this.form.roleName = "";
          this.form.roleCode = "";
          this.$nextTick(() => {
            this.$refs["form"].resetFields();
          });
          this.dialogFormVisible = true;
        }
      })
    },

    // 修改
    handleModify(row) {
      this.title = "修改角色";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.form.id = row.id;
        this.form.roleName = row.role_name;
        this.form.roleCode = row.role_code;
      });
    },

    // 删除
    handleDelete(row) {
      this.$confirm("此操作将删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delUserRole(row.id).then((res) => {
            this.$message({
              message: "删除成功",
              type: "success",
            });
            this.getPageList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 输入字数限制
    changeValue(attr, byte) {
      let value = this.form[attr]; //校验的字段
      // 中文、中文标点、全角字符按1长度，英文、英文符号、数字按0.5长度计算
      let cnReg = /([\u4e00-\u9fa5]|[\u3000-\u303F]|[\uFF00-\uFF60])/;
      let maxLimitStr = byte; //25个汉字
      let pass = true;
      let substringStr = "";
      let length = 0;
      let strArr = value.split("");
      strArr.map((str) => {
        if (pass) {
          if (cnReg.test(str)) {
            //中文
            length++;
          } else {
            //英文
            length += 0.5;
          }
          //大于最大限制的时候
          if (length > maxLimitStr) {
            pass = false;
            //将校验的字符截取返回
            this.form[attr] = substringStr;
          } else {
            substringStr += str;
          }
        }
      });
      return pass;
    }
  },
};
</script>


<style lang="scss" scoped>
.filter-container {
  display: flex;
  justify-content: space-between;
}

.Charge-left {
  width: 375px;
  // height: 800px;
}

.Charge-left {
  width: 525px;
  // height: 800px;
}
</style>

<style>
.el-tooltip__popper {
  max-width: 30%;
}
.project_name{
  display: flex;
  align-content: center;
  justify-content: space-between;
}
</style>
